import time

from loguru import logger
from DrissionPage import Chromium
import pandas as pd
from read_search_file import get_search_comp, get_complete_sheet1

def log_message(log_callback, message, color=None):
    if callable(log_callback):
        log_callback(message, color) if color else log_callback(message)

def create_creative_func(creative_view_tab, r_excel, browser, file_path, unit_next_button_ele=None, log_callback=None):
    ## 读取转化组件sheet
    df_search_comp = get_search_comp(file_path)
    creative_view_tab.wait.load_start()

    logger.info(f"进入创意界面")
    img_all_select = r_excel['封面全选']
    note_ids_arr = r_excel['笔记ID']
    indus_qualification = r_excel['行业资质']
    auto_optimize = r_excel['自动优化'] if pd.notna(r_excel['自动优化']) else "关闭"

    items = creative_view_tab.ele('css:.form-content > .group').eles('.item')

    for i, item in enumerate(items):
        item('tag:input@@class=d-text@@type=text@@placeholder=请输入你的创意名称').scroll.to_center()
        creative_name_ele = item('tag:input@@class=d-text@@type=text@@placeholder=请输入你的创意名称', timeout=15)
        # creative_view_tab.wait.eles_loaded('tag:input@@class=d-text@@type=text@@placeholder=请输入你的创意名称')  # 等待元素加载

        current_note_id = item('css:.d-table__body > tr > td:nth-child(2)').text

        star_name = item('css:.d-table__body > tr > td:nth-child(4)').text

        if current_note_id not in note_ids_arr:
            log_message(log_callback, f"当前笔记ID:{current_note_id}-达人昵称:{star_name}在转化组件中没有匹配值, 默认转化组件选【无】", "red")

        # 如果存在创意名称用自定义创意名称，否则默认达人昵称
        if '创意名称' in df_search_comp.columns:
            for d in df_search_comp.itertuples():
                if current_note_id != d.笔记ID.strip():
                    continue
                excel_creative_name = d.创意名称

                if pd.notna(excel_creative_name):
                    # creative_name_ele.input(excel_creative_name, clear=True)  # 填写创意名称
                    creative_name_ele.run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', excel_creative_name)  # 填写创意名称
                    break
                else:
                    creative_name_ele.input(star_name, clear=True)  # 填写创意名称
                    break
        else:
            creative_name_ele.input(star_name, clear=True)  # 填写创意名称

        # 处理监测链接
        if '监测链接' in df_search_comp.columns:
            for d in df_search_comp.itertuples():
                if current_note_id != d.笔记ID.strip():
                    continue
                monitor_link = d.监测链接
                if pd.notna(monitor_link):
                    monitor_link = monitor_link.strip()
                    if edit_monitor_link := item('tag:div@@text()=修改监测链接', timeout=1):
                        edit_monitor_link.click(by_js=True, timeout=3)
                        creative_view_tab.wait(0.5)
                        creative_view_tab.ele('tag:input@@class=d-text@@placeholder=请输入链接').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', monitor_link)
                        creative_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=保存').parent(2).click(by_js=True)  # 保存链接
                    else:
                        # while True:
                        #     if not item('tag:div@@text()=添加监测链接', timeout=1.5):
                        #         break
                        add_monitor_link_repeat(creative_view_tab, item, monitor_link)
                break
        # 第一个标签页编辑投放资质之后绑定至所有创意
        if i == 0:
            item('tag:span@@class=link-text@@text()=编辑').wait(.5).click(by_js=True)

            if creative_view_tab.ele('tag:button@@text()=继续修改', timeout=2):
                logger.info("投放资质存在继续修改按钮")
                creative_view_tab.ele('tag:button@@text()=继续修改', timeout=2).click(by_js=True)

            # 选中行业资质具体内容
            if indus_qualification_content_ele := creative_view_tab.ele(f'tag:div@@class=d-grid d-option d-option-content --color-text-title@@text()={indus_qualification.strip()}', timeout=2):
                indus_qualification_content_ele.run_js('this.click()') # 选中具体资质内容
            else:
                creative_view_tab.ele('css:.d-options-wrapper > .d-grid  > .d-grid-item:nth-child(1)', timeout=2).wait.displayed()
                creative_view_tab.ele('css:.d-options-wrapper > .d-grid  > .d-grid-item:nth-child(1)', timeout=2).run_js('this.click()')


            if all_bind_ele := creative_view_tab.ele('tag:span@@text()= 绑定至所有创意 ', timeout=2):  # 点击绑定当前创意
                all_bind_ele.parent(2).click(by_js=True)  # 点击绑定所有创意
            elif current_bind_ele := creative_view_tab.ele('tag:span@@text()= 绑定至当前创意 ', timeout=2):
                current_bind_ele.parent(2).click(by_js=True)  # 点击绑定当前创意
            else:
                creative_view_tab.ele('tag:span@@text()= 取消 ', timeout=2).click(by_js=True)

            if creative_view_tab.ele('tag:button@@text()=确认修改', timeout=1):
                logger.info("投放资质存在确认修改按钮")
                creative_view_tab.ele('tag:button@@text()=确认修改').click(by_js=True)

        # 创意素材
        if img_all_select == '否':
            if item('tag:a@@text()=添加封面', timeout=2):
                item('tag:a@@text()=添加封面').scroll.to_center()
                item('tag:a@@text()=添加封面').click(by_js=True)
            if item('tag:a@@text()=选择封面', timeout=2):
                item('tag:a@@text()=选择封面').scroll.to_center()
                item('tag:a@@text()=选择封面').click(by_js=True)

            creative_view_tab.wait(1)

            img_all_select_left_eles = creative_view_tab.eles('css:.modal-content-left-covers > .photo-item')
            img_all_select_eles = creative_view_tab.eles('css:.modal-content-right > .select-photo-item')

            if len(img_all_select_left_eles) == len(img_all_select_eles):
                # creative_view_tab.wait.eles_loaded('tag:span@@text()=全选')
                creative_view_tab.ele('tag:span@@text()=全选').click(by_js=True)
                time.sleep(1)
                creative_view_tab.ele('tag:span@@text()= 确认选择 ').click(by_js=True)
            else:
                if len(img_all_select_eles) > 1:
                    creative_view_tab.ele('tag:span@@text()=全选').click(by_js=True)
                    creative_view_tab.ele('tag:span@@text()=全选').click(by_js=True)
                    creative_view_tab.ele('tag:span@@text()= 确认选择 ').click(by_js=True)
                else:
                    creative_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 取消 ').click(by_js=True)
        else:
            if item('tag:a@@text()=添加封面', timeout=2):
                item('tag:a@@text()=添加封面').scroll.to_center()
                item('tag:a@@text()=添加封面').click(by_js=True)
            if item('tag:a@@text()=选择封面', timeout=2):
                item('tag:a@@text()=选择封面').scroll.to_center()
                item('tag:a@@text()=选择封面').click(by_js=True)

            creative_view_tab.wait(1)
            img_all_select_left_eles = creative_view_tab.eles('css:.modal-content-left-covers > .photo-item')
            img_all_select_eles = creative_view_tab.eles('css:.modal-content-right > .select-photo-item')

            if len(img_all_select_left_eles) > len(img_all_select_eles) or len(img_all_select_eles) == 1:
                creative_view_tab.ele('tag:span@@text()=全选').click(by_js=True)
                time.sleep(1)
                creative_view_tab.ele('tag:span@@text()= 确认选择 ').click(by_js=True)
            else:
                creative_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 取消 ').click(by_js=True)

        item(f'tag:div@@class=flexible align-center@@text()={auto_optimize}').click(by_js=True)  # 自动优化

        ## 处理转化组件
        item(f'tag:span@@text()=转化组件').scroll.to_center()  # 滚到转化组件

        if item(f'tag:span@@text()=搜索组件', timeout=1):
            if not df_search_comp.empty:
                for s in df_search_comp.itertuples():
                    if current_note_id != s.笔记ID.strip():
                        continue
                    trans_comp = s.转化组件.strip()

                    item(f'tag:span@@text()={trans_comp}').scroll.to_center()
                    item(f'tag:span@@text()={trans_comp}').parent(1).click(by_js=True)  # 点击转化组件

                    if trans_comp == '搜索组件':
                        item('tag:span@@text()=图片或视频底部').scroll.to_center()
                        img_or_video_ele = item('tag:span@@text()=图片或视频底部')
                        img_or_video_ele_str = img_or_video_ele.prev().prev().attr('class')
                        if 'unchecked' not in img_or_video_ele_str:
                            img_or_video_ele.parent(1).click(by_js=True)  # 先取消图片或视频底部默认选中

                        top_comment_ele = item('tag:span@@text()=置顶评论')
                        top_comment_ele_str = top_comment_ele.prev().prev().attr('class')
                        if 'unchecked' not in top_comment_ele_str:
                            top_comment_ele.parent(1).click(by_js=True)  # 先取消置顶评论默认选中

                        search_word = s.搜索词 if s.搜索词 else ""

                        comp_loc_arr = s.组件位置.strip().split('\n')  ## 组件位置
                        for comp in comp_loc_arr:
                            if comp == '图片或视频底部':
                                item('tag:span@@text()=图片或视频底部').parent(1).wait(0.5).click(by_js=True)  # 点击图片或视频底部
                                item('tag:input@@class=d-text@@type=text@@placeholder=请输入搜索词').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', search_word)  # 输入搜索词
                            if comp == '置顶评论':
                                item('tag:span@@text()=置顶评论').parent(1).wait(0.5).click(by_js=True)  # 点击置顶评论
                                item('css:.conversion-group > .input > .comment-input-box input[placeholder="请输入置顶评论文案"]').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', s.置顶评论文案)  # 点击图片或视频底部
                                item('tag:input@@class=d-text@@type=text@@placeholder=请输入搜索词').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', search_word)  # 点击图片或视频底部
                    break

    creative_view_tab.ele('css:.footer-action .d-button:nth-child(2)').click(by_js=True)  # 点击创意层级完成
    if not item('tag:span@@class=error@@text():请选择组件的位置', timeout=1) and not item('tag:span@@class=error@@text():请填写搜索词', timeout=1) and not item('tag:span@@class=error@@text():请输入评论文案，默认项为必填', timeout=1):
        browser.close_tabs(creative_view_tab)
        logger.info(f"创意完成")

def add_monitor_link_repeat(creative_view_tab, item, monitor_link):
    if add_monitor_link := item('tag:div@@text()=添加监测链接', timeout=2):
        add_monitor_link.click(by_js=True, timeout=3)  # 点击添加监测链接
        creative_view_tab.wait(0.5)
        monitor_link_arr = monitor_link.strip().split('\n')
        for monitor in monitor_link_arr:
            creative_view_tab.ele('tag:span@@text()=点击监测链接').next().ele('tag:span@@class=add-action@@text()= 添加 ').click(by_js=True, timeout=3)  # 点击添加
            creative_view_tab.ele('tag:div@@class=err-tips@@text()=请输入监测链接').wait.displayed()
            # creative_view_tab.ele('tag:div@@class=err-tips@@text()=请输入监测链接').prev().ele('tag:input@@class=d-text@@placeholder=请输入链接').input(monitor, clear=True)  # 输入链接
            creative_view_tab.ele('tag:div@@class=err-tips@@text()=请输入监测链接').prev().ele('tag:input@@class=d-text@@placeholder=请输入链接').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', monitor)
        creative_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=保存').parent(2).click(by_js=True)  # 保存链接


# if __name__ == '__main__':
#     file_path = r"D:\Users\Desktop\搜索-创建计划-样例（5月计划.xlsx"
#
#     browser = Chromium()  ## 临时测试、到时候删掉， 只保留调用create_unit()函数
#     unit_view_tab = browser.latest_tab  ## 临时测试、到时候删掉
#     unit_view_tab.get('https://ad.xiaohongshu.com/aurora/ad/create/creativity/119720230/261889292/4/1/2?isStep=true&from=CampaignList&AFormGrayFlag=false&vSellerId=63be38f04ee9db000147041b')  ## 临时测试、到时候删掉
#
#     sheet1_data = get_complete_sheet1(file_path)
#     for index, row in sheet1_data.iterrows():
#         if index == 0:
#             create_creative_func(unit_view_tab, row, browser, file_path, ['123', '122222'])
